<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

interface Props {
  visible: boolean;
  pet?: any;
  customer?: any;
}

interface Emits {
  (e: 'update:visible',value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();

// 表单数据
const formData = ref({
  name: '',
  id: '',
  birthday: null,
  gender: '',
  type: '',
  ageYears: undefined,
  ageMonths: undefined,
  color: '',
  breed: '',
  neutered: false,
  dewormed: false,
  vaccinated: false,
  deceased: false,
  notes: '',
});

// 计算属性
const isEdit = computed(() => !!props.pet);

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入宠物名字' }],
  gender: [{ required: true, message: '请选择性别' }],
  type: [{ required: true, message: '请选择种类' }],
};

// 方法
const getPetIcon = () => {
  const type = formData.value.type;
  switch (type) {
    case 'bird': {
      return '🐦';
    }
    case 'cat': {
      return '🐱';
    }
    case 'dog': {
      return '🐕';
    }
    case 'rabbit': {
      return '🐰';
    }
    default: {
      return '🐾';
    }
  }
};

const getLastPetId = () => {
  if (!props.customer || props.customer.pets.length === 0) {
    return 'P000001';
  }
  const lastPet = props.customer.pets[props.customer.pets.length - 1];
  return lastPet.id;
};

const generateNewId = () => {
  const lastId = getLastPetId();
  const num = Number.parseInt(lastId.slice(1)) + 1;
  formData.value.id = `P${num.toString().padStart(6, '0')}`;
};

const resetForm = () => {
  formData.value = {
    name: '',
    id: '',
    birthday: null,
    gender: '',
    type: '',
    ageYears: undefined,
    ageMonths: undefined,
    color: '',
    breed: '',
    neutered: false,
    dewormed: false,
    vaccinated: false,
    deceased: false,
    notes: '',
  };
};

// 监听宠物变化
watch(
  () => props.pet,
  (pet) => {
    if (pet) {
      // 编辑模式，填充表单数据
      formData.value = {
        name: pet.name,
        id: pet.id,
        birthday: pet.birthday ? dayjs(pet.birthday) : null,
        gender: pet.gender,
        type: pet.type,
        ageYears: pet.age,
        ageMonths: 0,
        color: pet.color,
        breed: pet.breed,
        neutered: pet.neutered,
        dewormed: pet.dewormed,
        vaccinated: pet.vaccinated,
        deceased: pet.deceased,
        notes: pet.notes || '',
      };
    } else {
      // 新增模式，重置表单并生成新ID
      resetForm();
      generateNewId();
    }
  },
  { immediate: true },
);

const handleOk = async () => {
  try {
    await formRef.value?.validate();

    // 这里可以调用API保存宠物数据
    message.success(isEdit.value ? '宠物信息修改成功' : '宠物创建成功');
    emit('success');
    emit('update:visible', false);
    resetForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  emit('update:visible', false);
  resetForm();
};
</script>

<template>
  <a-modal
    :open="visible"
    :title="isEdit ? '修改宠物信息' : '新增宠物'"
    width="700px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="头像">
            <div class="avatar-upload">
              <a-avatar :size="80" style="background: #1890ff">
                {{ getPetIcon() }}
              </a-avatar>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="名字" name="name">
            <a-input
              v-model:value="formData.name"
              placeholder="请输入宠物名字"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="编号">
            <a-input
              v-model:value="formData.id"
              placeholder="编号自动生成"
              disabled
            />
            <div class="form-tip">
              (温馨提示:最近使用的编号为{{ getLastPetId() }})
            </div>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="8">
          <a-form-item label="生日" name="birthday">
            <a-date-picker
              v-model:value="formData.birthday"
              placeholder="请选择生日"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="性别" name="gender">
            <a-select v-model:value="formData.gender" placeholder="请选择性别">
              <a-select-option value="male">公</a-select-option>
              <a-select-option value="female">母</a-select-option>
              <a-select-option value="unknown">未知</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="种类" name="type">
            <a-select v-model:value="formData.type" placeholder="请选择种类">
              <a-select-option value="dog">狗狗</a-select-option>
              <a-select-option value="cat">猫咪</a-select-option>
              <a-select-option value="bird">鸟类</a-select-option>
              <a-select-option value="rabbit">兔子</a-select-option>
              <a-select-option value="other">其他</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="6">
          <a-form-item label="年龄(岁)" name="ageYears">
            <a-input-number
              v-model:value="formData.ageYears"
              placeholder="岁"
              :min="0"
              :max="30"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="年龄(月)" name="ageMonths">
            <a-input-number
              v-model:value="formData.ageMonths"
              placeholder="月"
              :min="0"
              :max="11"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="毛色" name="color">
            <a-select
              v-model:value="formData.color"
              placeholder="请选择毛色"
              allow-clear
            >
              <a-select-option value="黑色">黑色</a-select-option>
              <a-select-option value="白色">白色</a-select-option>
              <a-select-option value="黄色">黄色</a-select-option>
              <a-select-option value="灰色">灰色</a-select-option>
              <a-select-option value="棕色">棕色</a-select-option>
              <a-select-option value="花色">花色</a-select-option>
              <a-select-option value="其他">其他</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="品种" name="breed">
            <a-select
              v-model:value="formData.breed"
              placeholder="请选择品种"
              allow-clear
            >
              <a-select-option value="金毛">金毛</a-select-option>
              <a-select-option value="拉布拉多">拉布拉多</a-select-option>
              <a-select-option value="英短">英短</a-select-option>
              <a-select-option value="美短">美短</a-select-option>
              <a-select-option value="其他">其他</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="其他">
        <a-space>
          <a-checkbox v-model:checked="formData.neutered">已去势</a-checkbox>
          <a-checkbox v-model:checked="formData.dewormed">已驱虫</a-checkbox>
          <a-checkbox v-model:checked="formData.vaccinated">已免疫</a-checkbox>
          <a-checkbox v-model:checked="formData.deceased">已死亡</a-checkbox>
        </a-space>
        <div class="form-tip">宠物状态标识</div>
      </a-form-item>

      <a-form-item label="备注" name="notes">
        <a-textarea
          v-model:value="formData.notes"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
.avatar-upload {
  text-align: center;
}

.form-tip {
  margin-top: 4px;
  font-size: 12px;
  color: #999;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style>
